package com.zhongying.jf.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class WeightRandom {

    private Random r;

    private static WeightRandom instance = new WeightRandom();

    public static WeightRandom getInstance(){
        return instance;
    }

    private WeightRandom(){
        r= new Random();
    }

    public int getWeightRandom(double[] weightArrays) {
        double weightSum = weightArraySum(weightArrays);
        double stepWeightSum = 0;
        for (int i = 0; i < weightArrays.length; i++) {
            stepWeightSum += weightArrays[i];
            if (Math.random() <= stepWeightSum / weightSum) {
                return i;
            }
        }
        return -1;
    }

    private double weightArraySum(double[] weightArrays) {
        double weightSum = 0;
        for (double weightValue : weightArrays) {
            weightSum += weightValue;
        }
        return weightSum;
    }

    public float randomValue(int begin,int end){
        List<Integer> range = new ArrayList<>();
        int i = begin*10;
        while (end*10>i){
            i++;
            range.add(i);
        }
        return Float.valueOf(range.get(new Random().nextInt(range.size())))/10;
    }
}